//
//  HMNavigationController.swift
//  Weibo
//
//  Created by teacher on 2017/6/4.
//  Copyright © 2017年 teacher. All rights reserved.
//

import UIKit
//  自定义导航视图控制器
class HMNavigationController: UINavigationController, UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //  设置屏幕边缘手势代理
        self.interactivePopGestureRecognizer?.delegate = self
        
    }
    
    //  重写push方法判断导航控制器里面的子视图控制器的个数
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        
        if viewControllers.count > 0 {
            if viewControllers.count == 1 {
                //  获取第一级控制器标题
                let title = viewControllers.first!.title
                //  设置viewController的leftButtonitem
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: title!,imageName: "navigationbar_back_withtext", target: self, action: #selector(backAction))
            } else {
                //  设置viewController的leftButtonitem设置成为返回
                //  leftBarButtonItem 边缘收拾就不可用了
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", imageName: "navigationbar_back_withtext", target: self, action: #selector(backAction))
            }
            
            viewController.title = "当前显示的是第\(viewControllers.count + 1)级控制器"
            //  除了根视图控制器push的时候都需要隐藏tabbar，会出现push黑影效果
            //  解决办法
            //  1.设置window的背景色
            //  2.设置tabbar的背景图片
            viewController.hidesBottomBarWhenPushed = true
        }
        
                
        super.pushViewController(viewController, animated: animated)    //  执行完这句代码以后这个视图控制器才压栈到导航视图控制器里面
    
        
    }

    
    //  MARK:   --点击返回按钮的操作
    @objc private func backAction() {
        
        self.popViewController(animated: true)
    }
    
    //  MARK:   ---UIGestureRecognizerDelegate
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        //  如果是根视图控制器，不需要开启边缘手势
        if viewControllers.count == 1 {
            return false
        }
        
        //  开启边缘手势
        return true
        
    }
    

}
